package com.szxb.facebus.util.sound;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

import com.szxb.facebus.R;
import com.szxb.mlog.SLog;


/**
 * 作者: Tangren on 2017-09-05
 * 包名：szxb.com.commonbus.util.sound
 * 邮箱：996489865@qq.com
 * 音源管理
 */

public class SoundPoolUtil {

    private static SoundPool mSoundPlayer = new SoundPool(1,
            AudioManager.STREAM_MUSIC, 5);
    private static SoundPoolUtil soundPlayUtils;
    private static MediaPlayer mediaPlayer;

    private static Context mContext;

    private static int sounds[] = new int[]{
            R.raw.music_face_success,
            R.raw.music_face_fail,
            R.raw.scan_success,
            R.raw.scan_verify_fail,
            R.raw.scan_qr
    };

    /**
     * 初始化
     *
     * @param context .
     */
    public static SoundPoolUtil init(Context context) {
        if (soundPlayUtils == null) {
            soundPlayUtils = new SoundPoolUtil();
        }
        mContext = context.getApplicationContext();
        for (int sound : sounds) {
            mSoundPlayer.load(mContext, sound, 1);
        }
        return soundPlayUtils;
    }


    /**
     * 播放声音
     *
     * @param soundID .
     */
    public synchronized static void play(int soundID) {
        int play = mSoundPlayer.play(soundID, 1, 1, 0, 0, 1);
        if (play == 0) {
            SLog.e("SoundPoolUtil(play.java:84)SoundPoolUtil播放失败>>音源ID=" + soundID);
            if (soundID > 0) {
                SLog.e("SoundPoolUtil(play.java:87)使用playMedia播放");
                playMedia(sounds[soundID - 1]);
            }
        }
    }

    private static void playMedia(int soundID) {
        try {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }

            mediaPlayer = MediaPlayer.create(mContext, soundID);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setLooping(false);
            mediaPlayer.start();

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            SLog.e("SoundPoolUtil(playMedia.java:106)playMedia播放异常>>>soundID=" + soundID + ">>>>>>>" + e.toString());
        }

    }

}
